package com.sansecy.customview;

import android.content.Context;
import android.content.res.Configuration;
import android.util.DisplayMetrics;
import android.util.TypedValue;

/**
 * 常用单位转换的辅助类
 * <p>
 * 作者：hexiang
 * 时间：2018/11/29 下午4:18
 * 修改人：
 * 修改时间：
 * 修改备注：
 */

public class DensityUtils {
    private DensityUtils() {
        /* cannot be instantiated */
        throw new UnsupportedOperationException("cannot be instantiated");
    }

    /**
     * dp转px
     *
     * @param context
     * @return
     */
    public static int dp2px(Context context, float dpVal) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                dpVal, context.getResources().getDisplayMetrics());
    }

    /**
     * sp转px
     *
     * @param context
     * @return
     */
    public static int sp2px(Context context, float spVal) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
                spVal, context.getResources().getDisplayMetrics());
    }

    /**
     * px转dp
     *
     * @param context
     * @param pxVal
     * @return
     */
    public static float px2dp(Context context, float pxVal) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (pxVal / scale);
    }

    /**
     * px转sp
     *
     * @param pxVal
     * @return
     */
    public static float px2sp(Context context, float pxVal) {
        return (pxVal / context.getResources().getDisplayMetrics().scaledDensity);
    }

    public static void changeDensity(Context context, int fontScale, int densityDpi) {
        //desiredDensity : ldpi = 0.75 (120dpi) , mdpi = 1 (160dpi), hdpi = 1.5 (240dpi), xhdpi = 2.0 (320dpi)
        DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        android.content.res.Configuration configuration = context.getResources().getConfiguration();
        configuration.fontScale = metrics.scaledDensity;
        configuration.fontScale = fontScale;
        configuration.densityDpi = densityDpi;
        context.getResources().updateConfiguration(configuration, metrics);
    }

    public static void fitPhoneAndTablet(Context context) {
        DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        android.content.res.Configuration configuration = context.getResources().getConfiguration();
        configuration.fontScale = 1;
        if (configuration.densityDpi > 240) {
            configuration.densityDpi = 240;
        }
        context.getResources().updateConfiguration(configuration, metrics);
    }

    public static boolean isTablet(Context context) {
        boolean xlarge = ((context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == 4);
        boolean large = ((context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE);
        return xlarge || large;
    }
}
